package net.hvacapp.cmvrfforandroid.ui.project;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.mirror.android.common.util.StringUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.manager.ProjectManager;
import net.hvacapp.cmvrfforandroid.ui.BaseActivity;
import net.hvacapp.cmvrfforandroid.ui.MainTabBarActivity;
import net.hvacapp.cmvrfforandroid.ui.project.model.EquiptPriceData;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetEquiptPriceDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetProjectInfoDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetProjectTempleteDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.ProjectInfoData;
import net.hvacapp.cmvrfforandroid.ui.project.model.ProjectTempleteData;
import net.hvacapp.cmvrfforandroid.ui.project.view.TwoLinesCellView;
import net.hvacapp.cmvrfforandroid.ui.selections.model.AreaData;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;
import net.hvacapp.cmvrfforandroid.utils.NumberUtil;
import net.hvacapp.cmvrfforandroid.widget.ProjectActionView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.HashMap;
import java.util.Map;

@EActivity(R.layout.activity_project_step9)
public class ProjectStep9Activity extends BaseActivity {

    @ViewById(R.id.action_view)
    ProjectActionView mActionView;

    @ViewById(R.id.other)
    TwoLinesCellView mOtherPrice;
    @ViewById(R.id.rate)
    TwoLinesCellView mTaxRate;
    @ViewById(R.id.charge)
    TwoLinesCellView mChargePrice;
    @ViewById(R.id.tv_total)
    TextView mTotalTv;


    private Dialog mProgressDlg;




    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initViews();
        initEvent();
    }

    /***
     * 初始化视图
     */
    private void initViews() {
        mActionView.setActionInfo(ProjectManager.getInstance().getTotal(), ProjectManager.getInstance().getCurrent());

        mOtherPrice.setTitleString("辅材&人工（元）");
        mOtherPrice.setItemSelected(true);
        mTaxRate.setTitleString("税率（%）");
        mTaxRate.setItemSelected(true);
        mChargePrice.setTitleString("成交价（元）");
        mChargePrice.setItemSelected(true);

    }

    private void setViewData() {
        ProjectInfoData data = ProjectManager.getInstance().getProjectData();
        mOtherPrice.setDescString(NumberUtil.formateMoney(data.getFuCaiPrice()));
        mTaxRate.setDescString(NumberUtil.formatDoublePercent(data.getTaxRate()));
        mChargePrice.setDescString(NumberUtil.formateMoney(data.getTransPrice()));

        String totalStr = "总价：" + NumberUtil.formateMoney(data.getTotalPrice());
        mTotalTv.setText(totalStr);
    }

    private void editPrice(final int type, String title) {
        final EditText priceEt = new EditText(this);
        priceEt.setKeyListener(new DigitsKeyListener(false, true));
        if (type == 1) {
            priceEt.setText(NumberUtil.formateDouble(ProjectManager.getInstance().getProjectData().getFuCaiPrice()));
        }
        else if (type == 2) {
            priceEt.setText(NumberUtil.formateDouble(ProjectManager.getInstance().getProjectData().getTaxRate()*100));
        }
        else {
            priceEt.setText(NumberUtil.formateDouble(ProjectManager.getInstance().getProjectData().getTransPrice()));
        }

        new AlertDialog.Builder(this).setTitle(title)
                .setView(priceEt)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            double price = Double.valueOf(priceEt.getText().toString());
                            if (price > 0) {
                                //修改报价
                                if (type == 1) {
                                    ProjectManager.getInstance().getProjectData().setFuCaiPrice(price);
                                }
                                else if (type == 2) {
                                    ProjectManager.getInstance().getProjectData().setTaxRate(price/100);
                                }
                                else {
                                    ProjectManager.getInstance().getProjectData().setTransPrice(price);
                                }
                                modifyProjectInfo(ProjectManager.getInstance().getProjectData());
                            }
                            else if (type == 3) {
                                ProjectManager.getInstance().getProjectData().setTransPrice(ProjectManager.getInstance().getProjectData().getTotalPrice());
                                modifyProjectInfo(ProjectManager.getInstance().getProjectData());
                            }
                            else {
                                showMessage("报价不能为0");
                            }
                        }
                        catch (Exception e) {

                        }
                    }
                })

                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 初始化
     */
    @Override
    public void initBoot() {
        setupToolbar(R.string.title_for_project, "其他报价", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(AnnotationUtil.get(MainTabBarActivity.class));
            }
        });
    }


    /**
     * 初始化数据
     */
    @Override
    public void initData(Intent intent) {
        loadProject(ProjectManager.getInstance().getProjectData().getGuidId());
    }



    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    private void initEvent() {
        mActionView.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //上一步
                ProjectManager.getInstance().goLastStep();
                finish();
            }
        });

        mActionView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下一步
//                ProjectManager.getInstance().goNextStep();
                startActivity(AnnotationUtil.get(BrowserActivity.class));
            }
        });

        mOtherPrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //编辑价格
                editPrice(1, "辅材&人工");
            }
        });

        mTaxRate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //编辑价格
                editPrice(2, "税率");
            }
        });

        mChargePrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //编辑价格
                editPrice(3, "成交价格");
            }
        });

    }

    private void loadProject(String guid) {
        Map<String, Object> param = new HashMap<>();
        param.put("pid", guid);

        mProgressDlg = createProgressBarDialog(this, "数据加载中...");
        mProgressDlg.show();

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_BY_GUID, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProjectInfoDataResp>() {
            @Override
            public void onSuccess(GetProjectInfoDataResp obj) {
                mProgressDlg.dismiss();
                // 成功
                ProjectManager.getInstance().setProjectData(obj.getGetProjectResult());
                //设置视图
                setViewData();
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
            }
        });
    }

    private void modifyProjectInfo(ProjectInfoData data) {
        Map<String, Object> param = new HashMap<>();
        param.put("prjInfo", data);

        BasicHttpClient.httpPostAsync(HttpConstant.HTTP_POST_PROJECT_INFO, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProjectInfoDataResp>() {
            @Override
            public void onSuccess(GetProjectInfoDataResp obj) {
                //需要重新拉取所有的系统数据
                ProjectManager.getInstance().setProjectData(obj.getModifyResult());
                setViewData();
            }

            @Override
            public void onFailure(String response) {
                showMessage("报价修改失败！");
            }
        });

    }


}
